Lux Log

December 15, 2007

Part 1 of 3 Basic example web app with Glassfish, NetBeans 6.0, JSF and EJB3

Filed under: Java, NetBeans — Luk @ 3:14 pm

Keywords: DAO, MVC, JSF, Session Facade, NetBeans 6.0, EJB3, GlassfishV2

If you’re looking for a walkthrough on setting up a basic web application using the DAO / MVC patterns with Glassfish V2 you’ve come to the right place. Here’s a HOWTO.

Upfront software requirements:

(If anyone wants this HOWTO/tutorial to be extended with instructions for MySQL post me a comment, if anyone wants a HOWTO on how to set up your environment post me a comment, if you get stuck at any certain point post me a comment…)

Please note that what you’ll find here are the bare essentials to give you a jumpstart. In the real world (and in later examples if this works out fine) Java goodies such as Seam and Facelets are added to make the steps below much simpler and much more attractive. Next to that, this example uses a simple datamodel with one domain element only (User). In a next step we might add more elements.

Table of contents

The example consists of two web pages, one enlisting all the users stored in the database, the other contains a form for adding a user.

10.png

20.png

Step 1: Create an Enterprise Application Project with NetBeans 6

  1. Start NetBeans
  2. Select Menubar item File > New Project …
  3. Select category Enterprise > project Enterprise Application
  4. Click Next
  5. Fill in Project Name JumpStartEjbJsf
  6. Click Finish

100.png

Step 2: Add JSF capabilities to your project

For now our web application only supports JSP. Let’s add JSF to the mix.

  1. Right-click the JumpStartEjbJsf-war created in Step 1 and select Properties.
  2. In the Project Properties dialog box select Frameworks.
  3. Click on Add.
  4. Select JavaServer Faces.
  5. Click OK.

200.png

If you’ve kept the default settings, when deployed JSF pages will be preceeded by /faces/. Therefore we have tell the container that index.jsp no longer is the start page but that faces/index.jsp is.

  1. In the Projects pane traverse through the tree to JumpStartEjbJsf-war > Configuration Files and open web.xml.
  2. Click on the Pages button in web.xml and change the value for Welcome Files to faces/index.jsp.
  3. Back in the Projects pane delete the file index.jsp
  4. Rename the file welcomeJSF.jsp to index.jsp

300.png

Step 3: Running the newly created project

Let’s check whether it is working. Press F6 to boot Glassfish, deploy the application and start up a browser window.

400.png

500.png

Step 4: Create the test_db database (on PostgreSQL)

Create a database using PgAdmin3 or by issuing the commands:

> sudo psql -U postgres
# CREATE DATABASE test_db WITH ENCODING=’UTF8′;
# \q

Create a table in our newly created test_db database by issuing the commands:

> sudo psql -U postgres -d test_db
# CREATE TABLE users
# (
# user_id serial,
# username varchar(255) NOT NULL,
# first_name varchar(255),
# last_name varchar(255),
# password char(64) NOT NULL,
# CONSTRAINT pk_users PRIMARY KEY (user_id)
#) WITHOUT OIDS;
# \q

Step 5: Add the JDBC driver file to Glassfish

If you have not yet setup a JDBC connection to PostgreSQL you have to add the right driver to Glassfish. Here are the steps:

  1. Download the JDBC driver for your version of PostgreSQL at http://jdbc.postgresql.org/download.html. I am using “JDBC3 Postgresql Driver, Version 8.2-507” with filename “postgresql-8.2-507.jdbc3.jar” since JDBC4 does not support all methods yet (like giving relevant feedback to the client when throwing an exception).
  2. Copy “postgresql-8.2-507.jdbc3.jar” to [GLASSFISH_DIR]/domains/domain1/lib.
  3. Restart the domain using the program asadmin available in [GLASSFISH_DIR]/bin.

>./asadmin stop-domain
>./asadmin start-domain

600.png

Step 6: Set up a JDBC connection pool in Glassfish

The next step is to set up a connection pool which we’ll use from our application to connect to the database.

1.
Go to the Admin Console at http://localhost:4848/. If you’ve kept the default username/password combination log in as “admin” with password “adminadmin” (and change it).

2.
Click Create New JDBC Connection Pool on the homepage.

3.
Fill in for New JDBC Connection Pool (Step 1 of 2):

Name: __PgTestDBPool
Resource type javax.sql.DataSource
Database Vendor PostgreSQL

4.
Fill in for New JDBC Connection Pool (Step 2 of 2) at the bottom of the page, assuming you kept default settings when installing PostgreSQL:

User postgres
DatabaseName test_db
Password xxxxxxxx
ServerName localhost
PortNumber 5432

5.
You are now directed to (look at the crumbpath) Resources > JDBC > Connection Pools. Click on your newly created JDNI entry __PgTestDBPool and click the Ping button at the top. A message should pop up saying Ping Succeeded.

700.png

6.
Now create a JDCB Resource by clicking Resources > JDBC > JDBC Resources in the left treeview pane

7.
On the JDBC Resources page click the New button and fill in:

JDNI Name jdbc/test_db
Pool Name __PgTestDBPool

Step 7: Create the User Entity Bean

In the next two steps we develop the backend application to define and expose our domain model. In this step we create the entity bean User which maps to the table we created in Step 4.

  1. In NetBeanse IDE right-click on JumpStartEjbJsf-ejb and select New > Entity Classes from Database…
  2. In the New Entity Classes From Database dialog box select Data Source: jdbc/test_db.
  3. In the New Database Connection that then pops up it should read the values from the table below…
  4. Click OK.
  5. On the next tab Advanced select Schema public.
  6. Back in the New Entity Classes From Database dialog box add the Users table to Selected Tables.
  7. Click Next.
  8. Change the class name from Users to User
  9. Fill in the package name lux.domain.
  10. Click the Create Persistence Unit button and accept the defaults.
  11. Uncheck Generate Named Query Annotations for Persistent Fields.
  12. Click Finish.
Name “PostgreSQL”
Driver “org.postgresql.Driver”
Database URL jdbc:postgresql://localhost:5432/test_db
Username postgres
Password xxxxxxxx

800.png

The only thing we change to the Entity Bean is to tell JPA to have the DB automatically generate ID’s for us. There might be better ways (if you’re interested post me a comment…) for doing this because now we are tied to PostgreSQL but hey. Another note up ahead is that the sequenceName is users_user_id_seq because this is the name of the sequence PostgreSQL generated for the serial datatype we used in our table definition in Step 4.

  1. Open the Entity Bean by clicking in the Projects pane: JumpStartEjbJsf-ejb > Source Packages > lux.domain > User.java.
  2. Change the code by adding the two lines below the comment:
@Entity
@Table(name = "Users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
// Add these two lines to the generated code
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="users_seq_generator")
@SequenceGenerator(name="users_seq_generator", sequenceName="users_user_id_seq")</strong>
@Column(name = "user_id", nullable = false)
private Integer id;

Import the necessary classes (one way is too put your cursor on the erronous reference, clicking Alt-Shift-I and select the class to import). These classes are referenced:

import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

Step 8: Add business logic

In this step we create a Stateless Session Bean as a facade to our domain object allowing us to get, create, delete or update objects. Just as the standard DAO pattern states.

  1. Create a Session Bean by right-clicking on “JumpStartEjbJsf-ejb” and selecting “New” > “Session Bean”
  2. In the “New Session Bean” dialog box: fill in
EJB Name UserDAO
Package lux.facade
Session type Stateless (default)
Create Interface Local (default)

900.png

You might consider providing both a Local (inside the JVM) and a Remote (for connecting to the component over the network) interface. But for this project it’s just Local. Therefore let’s change the name of the class from UserDAOLocal.java to UserDAO.java.

  1. In the Projects pane select JumpStartEjbJsf-ejb > Source Packages > lux.facade > UserDAOLocal.java and change the file name to UserDAO.java.
  2. Click Refactor.

Finally. Some code. If UserDAOBean.java is not open yet then open it. Change the existing code by the code below. If you want to know more about what is going on try the very good introductory book try Java EE 5 Development using GlassFish Application Server.

package lux.facade;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import lux.domain.User;

@Stateless
public class UserDAOBean implements UserDAO {

  @PersistenceContext
  private EntityManager em;

  public User getUser(int UserId) {
    User u = new User();
    u = em.find(User.class, UserId);
    return u;
  }

  public List<User> getAllUsers() {
    Query q = em.createQuery("SELECT u FROM User u");
    List<User> users = q.getResultList();
    return users;
  }

  public void createUser(User u) {
    String hashedPw = hashPassword(u.getPassword());
    u.setPassword(hashedPw);
    em.persist(u);
  }

  public void updateUser(User u) {
    String hashedPw = hashPassword(u.getPassword());
    u.setPassword(hashedPw);
    em.merge(u);
  }

  public void deleteUser(User u) {
    em.remove(u);
  }

  private String hashPassword(String password) {
    StringBuilder sb = new StringBuilder();
    try {
      MessageDigest messageDigest = MessageDigest.getInstance("SHA");
      byte[] bs;
      bs = messageDigest.digest(password.getBytes());
      for (int i = 0; i < bs.length; i++) {
        String hexVal = Integer.toHexString(0xFF & bs&#91;i&#93;);
        if (hexVal.length() == 1) {
          sb.append("0");
        }
        sb.append(hexVal);
      }
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(UserDAOBean.class.getName()).log(Level.SEVERE, null, ex);
    }
    return sb.toString();
  }
}&#91;/sourcecode&#93;
NetBeans will suggest you to update the Interface for each public method you add:<a href="https://luxlog.files.wordpress.com/2007/12/950.png" title="950.png"><img src="https://luxlog.files.wordpress.com/2007/12/950.thumbnail.png" alt="950.png" /></a>Here is the final source for the Interface.

package lux.facade;
import javax.ejb.Local;
@Local
public interface UserDAO {
  public lux.domain.User getUser(int UserId);
  public void createUser(lux.domain.User u);
  public void updateUser(lux.domain.User u);
  public void deleteUser(lux.domain.User u);
  public java.util.List<lux.domain.User> getAllUsers();
}

Feel like you’ve been doing lots of stuff? Well you have. You’ve got your application server running, made it possible to connect through it to a database, deployed an enterprise app running JSF, created a domain object and provided an interface to get and modify it.To the frontend now where we’ll create a list of users and a form to add a user to the database.

Step 9: Create the web application’s Controller

Next we create the controller class that will reference session facade created in Step 7.

1.
Create a controller (or “backing bean”) by right clicking JumpStartEjbJsf-war, selecting New > JSF Managed Bean. In the New JSF Managed Bean dialog box, fill in:

Class name UserController
Package lux.controllers
Scope session

1000.png

2.
Change the code for UserController.java to:

package lux.controllers;

import javax.ejb.EJB;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import lux.domain.User;
import lux.facade.UserDAO;

public class UserController {
  @EJB UserDAO userDao;
  private User user;
  private DataModel model;

  public String createUser() {
    this.user = new User();
    return “create_new_user”;
  }

  public String saveUser() {
    String r = “success”;
    try {
      userDao.createUser(user);
    } catch (Exception e) {
      e.printStackTrace();
      r = “failed”;
    }
    return r;
  }

  public DataModel getUsers() {
    model = new ListDataModel(userDao.getAllUsers());
    return model;
  }

  public User getUser() {
    return user;
  }

  public void setUser(User user) {
    this.user = user;
  }
}

The saveUser method above is the action that will be invoked when the user submits the form. Notice that saveUser returns either success or failed. This will decide to what page the user is forwarded as will be defined in faces-config.xml next.

Step 10: Configure page flow in faces-config.xml

  1. Create the JSP file adduser.jsp by right-clicking JumpStartEjbJsf-war and selecting New > JSP. Fill in File Name adduser.jsp, click Finish.
  2. Repeat the previous step for another JSP file failed.jsp.
  3. On failed.jsp change the string <h2>Hello world</h2> to <h2>Save failed</h2>.

1100.png

Next we configure the page flow.

  1. Open JumpStartEjbJsf-war > Configuration Files > faces-config.xml.
  2. Drag an arrow from index.jsf to adduser.jsp and replace the arrow’s label to create_new_user.
  3. Repeat the previous step for failed, by dragging and arrow from adduser.jsp to failed.jsp renaming the label to failed
  4. Finally repeat the step for adduser.jsp, by dragging from adduser.jsp to index.jsp renaming the label to success. This results in the image depicted below:

1200.png

1300.png

You’re faces-config should now look like this (click the “XML” button)

<?xml version='1.0' encoding='UTF-8'?>

<faces-config version="1.2"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd">
    <managed-bean>
        <managed-bean-name>user</managed-bean-name>
        <managed-bean-class>lux.controllers.UserController</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>
    <navigation-rule>
        <from-view-id>/index.jsp</from-view-id>
        <navigation-case>
            <from-outcome>create_new_user</from-outcome>
            <to-view-id>/adduser.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
    <navigation-rule>
        <from-view-id>/adduser.jsp</from-view-id>
        <navigation-case>
            <from-outcome>failed</from-outcome>
            <to-view-id>/failed.jsp</to-view-id>
        </navigation-case>
        <navigation-case>
            <from-outcome>success</from-outcome>
            <to-view-id>/index.jsp</to-view-id>
        </navigation-case>
    </navigation-rule>
</faces-config>

Last steps are writing the view elements (or “forms”).

Step 11: Create views

Open JumpStartEjbJsf-war > Web Pages > index.jsp and change the existing code by

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>User Listing</title>
    </head>
    <body>
        <f:view>
            <h:form>
                <h1><h:outputText value="User Listing"/></h1>
                <p><h:commandLink action="#{user.createUser}" value="Create a user"/></p>
                <h:dataTable value="#{user.users}"
                             var="dataTableItem" border="1" cellpadding="2" cellspacing="2">
                    <h:column>
                        <f:facet name="header">
                            <h:outputText  value="Username"/>
                        </f:facet>
                        <h:outputText value="#{dataTableItem.username}" />
                    </h:column>
                    <h:column>
                        <f:facet name="header">
                            <h:outputText  value="First name"/>
                        </f:facet>
                        <h:outputText value="#{dataTableItem.firstName}" />
                    </h:column>
                    <h:column>
                        <f:facet name="header">
                            <h:outputText  value="Last name"/>
                        </f:facet>
                        <h:outputText value="#{dataTableItem.lastName}" />
                    </h:column>
                </h:dataTable>
            </h:form>
        </f:view>
    </body>
</html>

Open JumpStartEjbJsf-war > Web Pages > adduser.jsp and change the existing code by

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%@taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@taglib prefix="h" uri="http://java.sun.com/jsf/html"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>New user</title>
    </head>
    <body>
        <f:view>
            <h:form>
                <h:messages/>
                <h:panelGrid columns="2">
                    <h:outputText value="Username"/>
                    <h:inputText
                        label="Username"
                        value="#{user.user.username}"
                        required="true"/>
                    <h:outputText value="First name"/>
                    <h:inputText
                        label="First name"
                        value="#{user.user.firstName}" />
                    <h:outputText value="Last name"/>
                    <h:inputText
                        label="Last name"
                        value="#{user.user.lastName}" />
                    <h:outputText value="Password" />
                    <h:inputSecret
                        label="Password"
                        value="#{user.user.password}"
                        required="true" />
                    <h:panelGroup/>
                    <h:commandButton
                        action="#{user.saveUser}"
                        value="Save"/>
                </h:panelGrid>
            </h:form>
        </f:view>
    </body>
</html>

Let’s run our application by clicking F6 (Run). If it doesn’t work right away because try “Undeploy and deploy”-ing it. I had to each time I walked through the above code for testing. You can do this by right-clicking the project name JumpStartEjbJsf and selecting Undeploy Deploy.Haven’t had enough already? Then there is Part 2: Basic web app extended to full CRUD

Hope it worked for you. Feel free to comment. What improvements can you think of? What should be the next move (integrate with SAAJ and make a login page)? Did you run into trouble? Let us know.

cc -Some rights

31 Comments »

  1. I enjoyed following through your example. However, when I went to deploy in Glassfish, I received the following error. Googling it returned few results. Any help would be appreciated.

    WebModule[/JumpStartEjbJsf-war]PWC1275: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener
    java.lang.NoClassDefFoundError: com/sun/data/provider/FieldKey

    Comment by sneeds — December 20, 2007 @ 5:46 pm

  2. This is a good example for a java student like me thanks

    Comment by Viral Patel — December 21, 2007 @ 1:25 am

  3. (To sneeds) It seems like you’re trying to call some class that hasn’t been initialized yet. Did this occur the first time you deployed (in step 3) or later, at the end? Does the error still occur if you first restart Glassfish and then try running the application again?

    Comment by Luk — December 21, 2007 @ 2:12 pm

  4. No sure what the issue was but I created a new project and used the same files and it works.

    Also, I had to make the controller ‘session’ in the faces-config in order to save. The controller ‘user’ object was null when I was submitting on the new user jsp — Moving on to Part 2. Many thanks.

    Comment by sneeds — December 21, 2007 @ 5:33 pm

  5. what i have to do cos when i follow instruction i get this error how i can repair it ?
    HTTP Status 500 –

    ——————————————————————————–

    type Exception report

    message

    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

    exception

    org.apache.jasper.JasperException: java.lang.RuntimeException: Cannot find FacesContext
    root cause

    java.lang.RuntimeException: Cannot find FacesContext
    note The full stack traces of the exception and its root causes are available in the Sun Java System Application Server 9.1 logs.

    ——————————————————————————–

    Sun Java System Application Server 9.1

    Comment by mustafa elamin — December 30, 2007 @ 4:40 pm

  6. Hey Mustafa,

    Check out the jee tutorial at http://java.sun.com/javaee/5/docs/tutorial/doc/bnaxj.html#bnaxl. It’s smth they will hopefully solve in future versions but for now “Before a JavaServer Faces application can launch the first JSP page, the web container must invoke the FacesServlet instance in order for the application life cycle process to start.”

    So, if you have followed the instructions correctly and you have adapted the web.xml file, I hope it will work if you undeploy and deploy the app, start the application server and manually browse to http://localhost:8080/JumpStartEjbJsf-war/faces/index.jsp. After that first manual action the FacesServlet instance should be invoked. Let me know if it worked.

    Comment by Luk — January 2, 2008 @ 10:11 am

  7. Hi,

    I tried to develop the application example you have provided but using JDeveloper IDE. I have created all EJB / JSF files and everything as specified but the problem I am facing is that INDEX.JSP pages load perfectly fine and when I click on Create a New Entry, it takes me to ADDUSER.jsp but when I provide data and click persist, DATA DOES NOT PERSIS TO THE DATABASE. WHat could be the issue?

    P.S. : I checked EJB individually by creating a Test Client application file and using println statements, it is working fine and printing those values to and from database but when I run the JSP pages, the desired output is not happenning.

    Comment by Nitin — January 20, 2008 @ 3:30 pm

  8. Hi,

    I am not sure why the data is not persisted. What you could do is to check logging info. To do this, change the log level in persistence.xml to FINE. This should output the SQL statements. If you’ve used the same persistence implementation as the default glassfish one (Toplink) then check http://www.oracle.com/technology/products/ias/toplink/jpa/howto/configure-logging.html for more info.

    Comment by Luk — January 23, 2008 @ 7:15 pm

  9. Really very nice tutorial.
    Exactly what I was looking for.
    Regards

    Comment by Alisson Patrick — January 28, 2008 @ 8:52 pm

  10. Hi

    I followed the instructions except I used mysql instead of postgre.
    I got the following exception:

    moduleID=JumpStartEjbJsf
    While redeploying, trying to stop the application in target server completed successfully
    While redeploying, trying to remove reference for application in target server completed successfully
    Deploying application in domain failed; Unrecognized module type for D:\workspace2\JumpStartEjbJsf\dist\gfdeploy; the archive may be incorrectly constructed, non-existent, or inaccessible from the server.
    For example, an application client jar should include the proper manifest file entry, and an ejb jar should contain at least one EJB.
    Deployment error:
    The module has not been deployed.
    See the server log for details.
    at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:163)
    at org.netbeans.modules.j2ee.ant.Deploy.execute(Deploy.java:104)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at sun.reflect.GeneratedMethodAccessor57.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:357)
    at org.apache.tools.ant.Target.performTasks(Target.java:385)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1298)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1181)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:277)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:460)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:151)
    Caused by: The module has not been deployed.
    at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:157)
    … 16 more
    BUILD FAILED (total time: 0 seconds)

    Any tips?
    I had to hardcode the implementation of UserDAO because of an other error message before:
    private @EJB(name=”mytest.facade.UserDAOBean”) UserDAO userDao;

    Thanks:
    Bence

    Comment by Bence Takacs — March 25, 2008 @ 1:39 pm

  11. Well, accidentally it started… I say accidentally, because I tried asadmin start/stop, and undeploy/deploy and restart netbeans in different combinations, and it worked only once out of 10. It seems that this was because of the known FacesContext issue…

    Now I can see the welcome page, but if I click on ‘Create a User’ it throws the following:
    javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘user’ resolved to null
    javax.faces.el.EvaluationException: javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘user’ resolved to null

    Any tips?

    Thanks
    Bence

    Comment by Bence Takacs — March 25, 2008 @ 2:46 pm

  12. This is an awesome example to a trainee programmer in java like me. Pls keep the good work going.

    I’m going through your examples and I’ll let you know any problem(s) in future.
    Best rgds.

    Comment by Victor — April 1, 2008 @ 12:42 pm

  13. I’m also getting the same error when trying to create a new user:

    javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘user’ resolved to null
    javax.faces.el.EvaluationException: javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘user’ resolved to null

    Please help! thanks 🙂

    Comment by violin00b — April 17, 2008 @ 7:53 am

  14. PS – I found the source for the error:
    javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘user’ resolved to null

    This is, in my case, due to faces-config.xml defaulting the names of the managed bean (controller) to what you specified as the class name (I think). For example, if you named it as UserController, the faces-config.xml will default the name to UserController, which is different from how index.jsp refers to it (as user). The server, when parsing index.jsp, will fail to find references to ‘user’ variable.

    Solution: change the value for the managed bean name to the correct one.
    From —

    UserController
    lux.controllers.UserController
    session

    To —

    user
    lux.controllers.UserController
    session

    in faces-config.xml.

    Hope this helps.

    Comment by violin00b — April 17, 2008 @ 8:44 am

  15. Thanks, this helps!

    Comment by Bence Takacs — April 26, 2008 @ 10:05 am

  16. Hello, Please Help, I could not build jsf/ejb3 application, some times I see NUll Point exception or etc. please provide full JSF/EJB3/JBOSS or Glassfish example, with JSF managed been to connect session beans.

    Comment by Armen — June 4, 2008 @ 2:07 pm

  17. I’m having a few problems with the 2 lines of code below the comments in step 7

    NetBeans has flagged the lines and has asked for identifiers.

    Some of the imports are also flagged as unused.

    It seems as though a brace is missing in the first line of code, but I’m not sure where the corresponding brace should go.

    Does anyone have the same problem and a possible solution?

    Thanks in advance

    Comment by Gilly — June 25, 2008 @ 4:39 pm

  18. Hi,

    i m getting below given error while deploying the above application.
    Cannot resolve reference Unresolved Ejb-Ref jdbc/test_db@jndi: @null@lux.facade.UserDAOBean@Session@null
    Exception occured in J2EEC Phasejava.lang.RuntimeException: Cannot resolve reference Unresolved Ejb-Ref jdbc/test_db@jndi: @null@lux.facade.UserDAOBean@Session@null
    com.sun.enterprise.deployment.backend.IASDeploymentException: Error loading deployment descriptors for module [JumpStartEjbJsf] — Cannot resolve reference Unresolved Ejb-Ref jdbc/test_db@jndi: @null@lux.facade.UserDAOBean@Session@null
    at com.sun.enterprise.deployment.backend.Deployer.loadDescriptors(Deployer.java:390)
    at com.sun.enterprise.deployment.backend.AppDeployerBase.loadDescriptors(AppDeployerBase.java:358)
    at com.sun.enterprise.deployment.backend.AppDeployer.explodeArchive(AppDeployer.java:294)
    at com.sun.enterprise.deployment.backend.AppDeployer.deploy(AppDeployer.java:207)
    at com.sun.enterprise.deployment.backend.AppDeployer.doRequestFinish(AppDeployer.java:148)
    at com.sun.enterprise.deployment.phasing.J2EECPhase.runPhase(J2EECPhase.java:191)
    at com.sun.enterprise.deployment.phasing.DeploymentPhase.executePhase(DeploymentPhase.java:108)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.executePhases(PEDeploymentService.java:919)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:279)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:788)
    at com.sun.enterprise.management.deploy.DeployThread.deploy(DeployThread.java:187)
    at com.sun.enterprise.management.deploy.DeployThread.run(DeployThread.java:223)
    Caused by: java.lang.RuntimeException: Cannot resolve reference Unresolved Ejb-Ref jdbc/test_db@jndi: @null@lux.facade.UserDAOBean@Session@null
    at com.sun.enterprise.deployment.util.EjbBundleValidator.accept(EjbBundleValidator.java:430)
    at com.sun.enterprise.deployment.WebBundleDescriptor.visit(WebBundleDescriptor.java:1406)
    at com.sun.enterprise.deployment.Application.visit(Application.java:1767)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.validate(ApplicationArchivist.java:470)
    at com.sun.enterprise.deployment.backend.Deployer.loadDescriptors(Deployer.java:366)
    … 11 more

    Please help me out.

    Thanks,
    Sachin

    Comment by Sachin — August 28, 2008 @ 12:10 pm

  19. The .jar must be included in [glassfish_home]/domains/domain1/lib/ext instead of [glassfish_home]/domains/domain1/lib, because when I did ping I have got an error.

    Comment by ana — September 3, 2008 @ 10:17 am

  20. Sir,
    This application is very useful to deploy . However, when i am using ejb/jsp and connecting with sql server.While i am clicking on “ping” I have error followed
    –>Class name is wrong or classpath is not set for : com.microsoft.sqlserver.jdbc.SQLServerDataSource

    Please send a solution to my mail id

    aim: i want to retrieve a emp details from sql server database table employee through ejb concept

    Comment by subhani — September 15, 2008 @ 8:03 am

  21. I have the same problem with the two line below the comments in step 7. Does anyone knows how to fix it?

    Comment by Gabriel — October 7, 2008 @ 7:44 pm

  22. Great article! It worked.Moving on to your next article….

    Comment by nitharc — November 27, 2008 @ 12:00 pm

  23. Hi,

    When i tried to run this application,i was able to see index.jsp when i clicked on Create a user i got the following exception.unable to find out where i went wrong..Plz help

    Thanks in advance.

    HTTP Status 500 –

    ——————————————————————————–

    type Exception report

    message

    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.

    exception

    javax.servlet.ServletException: #{User.createUser}: javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘User’ resolved to null
    root cause

    javax.faces.FacesException: #{User.createUser}: javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘User’ resolved to null
    root cause

    javax.faces.el.EvaluationException: javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘User’ resolved to null
    root cause

    javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘User’ resolved to null
    note The full stack traces of the exception and its root causes are available in the Sun Java System Application Server 9.1_02 logs.

    ——————————————————————————–

    Comment by Pradeep — January 9, 2009 @ 1:38 pm

  24. In adding the 2 lines to the User.java, I think you’ve erroneously included an HTML tag which shouldn’t be part of the line?

    Comment by Karen — March 24, 2009 @ 10:04 pm

  25. i couldnt make a connection betweeb adduser.jsp and index.jsp\
    please help me

    Comment by kava — April 22, 2009 @ 8:00 pm

  26. Thanks a lot for this excellent tutorial.
    Superb!!

    Comment by zaHir — May 19, 2009 @ 10:06 pm

  27. Hello

    I’ve been following this basic example, but I’m having a problem with the deployment of web project

    Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    Exception occured in J2EEC Phasejava.lang.RuntimeException: Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    com.sun.enterprise.deployment.backend.IASDeploymentException: Error loading deployment descriptors for module [EJB3_JSF-war] — Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    at com.sun.enterprise.deployment.backend.Deployer.loadDescriptors(Deployer.java:390)
    at com.sun.enterprise.deployment.backend.ModuleDeployer.loadDescriptors(ModuleDeployer.java:423)
    at com.sun.enterprise.deployment.backend.WebModuleDeployer.deploy(WebModuleDeployer.java:157)
    at com.sun.enterprise.deployment.backend.ModuleDeployer.doRequestFinish(ModuleDeployer.java:179)
    at com.sun.enterprise.deployment.phasing.J2EECPhase.runPhase(J2EECPhase.java:191)
    at com.sun.enterprise.deployment.phasing.DeploymentPhase.executePhase(DeploymentPhase.java:108)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.executePhases(PEDeploymentService.java:919)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:279)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:788)
    at com.sun.enterprise.management.deploy.DeployThread.deploy(DeployThread.java:187)
    at com.sun.enterprise.management.deploy.DeployThread.run(DeployThread.java:223)
    Caused by: java.lang.RuntimeException: Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    at com.sun.enterprise.deployment.util.EjbBundleValidator.accept(EjbBundleValidator.java:430)
    at com.sun.enterprise.deployment.WebBundleDescriptor.visit(WebBundleDescriptor.java:1406)
    at com.sun.enterprise.deployment.archivist.WebArchivist.validate(WebArchivist.java:188)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openArchive(ApplicationArchivist.java:790)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openArchive(ApplicationArchivist.java:744)
    at com.sun.enterprise.deployment.backend.Deployer.loadDescriptors(Deployer.java:349)
    … 10 more
    Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    Exception occured in J2EEC Phasejava.lang.RuntimeException: Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    com.sun.enterprise.deployment.backend.IASDeploymentException: Error loading deployment descriptors for module [EJB3_JSF-war] — Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    at com.sun.enterprise.deployment.backend.Deployer.loadDescriptors(Deployer.java:390)
    at com.sun.enterprise.deployment.backend.ModuleDeployer.loadDescriptors(ModuleDeployer.java:423)
    at com.sun.enterprise.deployment.backend.WebModuleDeployer.deploy(WebModuleDeployer.java:157)
    at com.sun.enterprise.deployment.backend.ModuleDeployer.doRequestFinish(ModuleDeployer.java:179)
    at com.sun.enterprise.deployment.phasing.J2EECPhase.runPhase(J2EECPhase.java:191)
    at com.sun.enterprise.deployment.phasing.DeploymentPhase.executePhase(DeploymentPhase.java:108)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.executePhases(PEDeploymentService.java:919)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:279)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:788)
    at com.sun.enterprise.management.deploy.DeployThread.deploy(DeployThread.java:187)
    at com.sun.enterprise.management.deploy.DeployThread.run(DeployThread.java:223)
    Caused by: java.lang.RuntimeException: Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    at com.sun.enterprise.deployment.util.EjbBundleValidator.accept(EjbBundleValidator.java:430)
    at com.sun.enterprise.deployment.WebBundleDescriptor.visit(WebBundleDescriptor.java:1406)
    at com.sun.enterprise.deployment.archivist.WebArchivist.validate(WebArchivist.java:188)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openArchive(ApplicationArchivist.java:790)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openArchive(ApplicationArchivist.java:744)
    at com.sun.enterprise.deployment.backend.Deployer.loadDescriptors(Deployer.java:349)
    … 10 more
    CORE5024: EJB module [EJB3_JSF-ejb] unloaded successfully!
    deployed with moduleid = EJB3_JSF-ejb
    LDR5010: All ejb(s) of [EJB3_JSF-ejb] loaded successfully!
    Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    Exception occured in J2EEC Phasejava.lang.RuntimeException: Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    com.sun.enterprise.deployment.backend.IASDeploymentException: Error loading deployment descriptors for module [EJB3_JSF-war] — Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    at com.sun.enterprise.deployment.backend.Deployer.loadDescriptors(Deployer.java:390)
    at com.sun.enterprise.deployment.backend.ModuleDeployer.loadDescriptors(ModuleDeployer.java:423)
    at com.sun.enterprise.deployment.backend.WebModuleDeployer.deploy(WebModuleDeployer.java:157)
    at com.sun.enterprise.deployment.backend.ModuleDeployer.doRequestFinish(ModuleDeployer.java:179)
    at com.sun.enterprise.deployment.phasing.J2EECPhase.runPhase(J2EECPhase.java:191)
    at com.sun.enterprise.deployment.phasing.DeploymentPhase.executePhase(DeploymentPhase.java:108)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.executePhases(PEDeploymentService.java:919)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:279)
    at com.sun.enterprise.deployment.phasing.PEDeploymentService.deploy(PEDeploymentService.java:788)
    at com.sun.enterprise.management.deploy.DeployThread.deploy(DeployThread.java:187)
    at com.sun.enterprise.management.deploy.DeployThread.run(DeployThread.java:223)
    Caused by: java.lang.RuntimeException: Cannot resolve reference Unresolved Ejb-Ref org.app.managed.user.UserManagedBean/businessBean@jndi: @null@org.app.business.BusinessLocal@Session@null
    at com.sun.enterprise.deployment.util.EjbBundleValidator.accept(EjbBundleValidator.java:430)
    at com.sun.enterprise.deployment.WebBundleDescriptor.visit(WebBundleDescriptor.java:1406)
    at com.sun.enterprise.deployment.archivist.WebArchivist.validate(WebArchivist.java:188)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openArchive(ApplicationArchivist.java:790)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openArchive(ApplicationArchivist.java:744)
    at com.sun.enterprise.deployment.backend.Deployer.loadDescriptors(Deployer.java:349)
    … 10 more

    What am I doing wrong?

    Comment by Julian Osorio Amaya — June 5, 2009 @ 3:50 pm

  28. I don’t know where is the GLASSFISH_DIR, let me know please

    Comment by Diana — February 6, 2010 @ 4:18 am

  29. Can I use your code with some modifications?

    Comment by Victor — January 5, 2011 @ 11:23 pm

  30. Diana something like that:
    GLASSFISH_DIR : C:\Program Files\glassfish-3.0.1\glassfish

    And this is the entire path to my GlassFish:
    C:\Program Files\glassfish-3.0.1\glassfish\domains\domain1\lib

    Comment by dinko — January 13, 2011 @ 10:35 pm

  31. I have this problem. Someone had something like this?
    Please help.
    An Error Occurred:

    An error occurred performing resource injection on user managed bean

    Previously, I had an error: javax.el.PropertyNotFoundException: Target Unreachable, identifier ‘user’ resolved to null
    tackled him, but after repairing it appeared:
    An Error Occurred:

    An error occurred performing resource injection on user managed bean

    Comment by dinko — January 13, 2011 @ 10:40 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.